<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>太空激战 - 像素飞行射击</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Courier New', monospace;
        }

        body {
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            overflow: hidden;
            padding: 20px;
        }

        #game-container {
            position: relative;
            width: 800px;
            max-width: 100%;
            text-align: center;
        }

        #game-header {
            background: rgba(0, 0, 0, 0.7);
            border: 3px solid #6a0dad;
            border-bottom: none;
            padding: 15px 20px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        #game-title {
            font-size: 2.2rem;
            letter-spacing: 3px;
            text-shadow: 0 0 10px #8a2be2, 0 0 20px #8a2be2;
            color: #e0b0ff;
            font-weight: bold;
        }

        .stat {
            background: rgba(138, 43, 226, 0.2);
            padding: 8px 15px;
            border-radius: 5px;
            font-size: 1.2rem;
            min-width: 120px;
            border: 1px solid #8a2be2;
        }

        #game-canvas {
            background: #000;
            border: 3px solid #6a0dad;
            display: block;
            margin: 0 auto;
            box-shadow: 0 0 30px rgba(138, 43, 226, 0.6);
        }

        #game-ui {
            background: rgba(0, 0, 0, 0.7);
            border: 3px solid #6a0dad;
            border-top: none;
            padding: 20px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
        }

        #game-message {
            font-size: 1.8rem;
            margin: 10px 0;
            min-height: 50px;
            color: #ffff00;
            text-shadow: 0 0 10px rgba(255, 255, 0, 0.7);
        }

        .btn {
            background: linear-gradient(to bottom, #8a2be2, #4b0082);
            color: white;
            border: none;
            padding: 12px 30px;
            font-size: 1.2rem;
            border-radius: 50px;
            cursor: pointer;
            margin: 10px 5px;
            transition: all 0.3s;
            font-weight: bold;
            letter-spacing: 1px;
        }

        .btn:hover {
            background: linear-gradient(to bottom, #9b42f5, #5c1a9c);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(138, 43, 226, 0.4);
        }

        .btn:active {
            transform: translateY(1px);
        }

        #controls {
            background: rgba(75, 0, 130, 0.3);
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #9370db;
        }

        .key {
            display: inline-block;
            background: rgba(138, 43, 226, 0.3);
            padding: 5px 10px;
            margin: 0 5px;
            border-radius: 5px;
            font-weight: bold;
            border: 1px solid #8a2be2;
        }

        #instructions {
            margin-top: 20px;
            font-size: 0.9rem;
            color: #d8bfd8;
            line-height: 1.6;
        }

        .stars {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
        }

        .star {
            position: absolute;
            background: #fff;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <div class="stars" id="stars"></div>

    <div id="game-container">
        <div id="game-header">
            <div class="stat">得分: <span id="score">0</span></div>
            <div id="game-title">太空激战</div>
            <div class="stat">生命: <span id="lives">3</span></div>
        </div>

        <canvas id="game-canvas" width="800" height="500"></canvas>

        <div id="game-ui">
            <div id="game-message">按开始按钮开始游戏!</div>
            <button id="start-btn" class="btn">开始游戏</button>
            <button id="restart-btn" class="btn">重新开始</button>

            <div id="controls">
                <p>移动: <span class="key">←</span> <span class="key">→</span> 射击: <span class="key">空格</span></p>
            </div>

            <div id="instructions">
                <p>躲避陨石和敌人飞船！射击敌人获取分数！每500分获得一条额外生命。</p>
            </div>
        </div>
    </div>

    <script>
        // 创建星星背景
        const starsContainer = document.getElementById('stars');
        for (let i = 0; i < 150; i++) {
            const star = document.createElement('div');
            star.classList.add('star');

            // 随机位置
            const x = Math.random() * 100;
            const y = Math.random() * 100;

            // 随机大小（0.5px - 2px）
            const size = Math.random() * 1.5 + 0.5;

            // 随机亮度（0.5 - 1）
            const brightness = Math.random() * 0.5 + 0.5;

            star.style.left = `${x}%`;
            star.style.top = `${y}%`;
            star.style.width = `${size}px`;
            star.style.height = `${size}px`;
            star.style.opacity = brightness;

            starsContainer.appendChild(star);
        }

        // 获取游戏元素
        const canvas = document.getElementById('game-canvas');
        const ctx = canvas.getContext('2d');
        const scoreDisplay = document.getElementById('score');
        const livesDisplay = document.getElementById('lives');
        const gameMessage = document.getElementById('game-message');
        const startBtn = document.getElementById('start-btn');
        const restartBtn = document.getElementById('restart-btn');

        // 游戏状态
        const game = {
            running: false,
            score: 0,
            lives: 3,
            level: 1,
            keys: {}
        };

        // 玩家飞船
        const player = {
            x: canvas.width / 2,
            y: canvas.height - 50,
            width: 60,
            height: 40,
            speed: 8,
            fireRate: 200, // 开火间隔(毫秒)
            lastShot: 0,
            color: '#00eeff'
        };

        // 子弹数组
        const bullets = [];

        // 敌机/陨石数组
        const enemies = [];

        // 粒子数组(用于爆炸特效)
        const particles = [];

        // 星星数组(用于背景)
        const bgStars = [];

        // 绘制玩家飞船
        function drawPlayer() {
            ctx.save();
            ctx.fillStyle = player.color;

            // 绘制飞船主体
            ctx.beginPath();
            ctx.moveTo(player.x, player.y - 15);
            ctx.lineTo(player.x - 20, player.y + 15);
            ctx.lineTo(player.x + 20, player.y + 15);
            ctx.closePath();
            ctx.fill();

            // 绘制飞船推进器
            ctx.fillStyle = '#ff5500';
            ctx.beginPath();
            ctx.moveTo(player.x - 15, player.y + 15);
            ctx.lineTo(player.x, player.y + 30);
            ctx.lineTo(player.x + 15, player.y + 15);
            ctx.closePath();
            ctx.fill();

            // 绘制飞船机翼
            ctx.fillStyle = '#00aaff';
            ctx.fillRect(player.x - 30, player.y, 15, 5);
            ctx.fillRect(player.x + 15, player.y, 15, 5);

            ctx.restore();
        }

        // 绘制子弹
        function drawBullets() {
            for (let i = 0; i < bullets.length; i++) {
                const b = bullets[i];
                ctx.save();
                ctx.fillStyle = '#ffff00';

                // 子弹头部
                ctx.beginPath();
                ctx.arc(b.x, b.y, 3, 0, Math.PI * 2);
                ctx.fill();

                // 子弹尾部
                ctx.beginPath();
                ctx.moveTo(b.x, b.y + 5);
                ctx.lineTo(b.x - 2, b.y + 12);
                ctx.lineTo(b.x + 2, b.y + 12);
                ctx.closePath();
                ctx.fillStyle = '#ff9900';
                ctx.fill();

                ctx.restore();
            }
        }

        // 绘制敌人
        function drawEnemies() {
            for (let i = 0; i < enemies.length; i++) {
                const e = enemies[i];
                ctx.save();

                if (e.type === 'asteroid') {
                    // 绘制陨石
                    ctx.fillStyle = '#aa8866';
                    ctx.beginPath();
                    ctx.arc(e.x, e.y, e.radius, 0, Math.PI * 2);
                    ctx.fill();

                    // 陨石表面的凹凸
                    ctx.fillStyle = '#996655';
                    ctx.beginPath();
                    ctx.arc(e.x - e.radius/3, e.y - e.radius/4, e.radius/3, 0, Math.PI * 2);
                    ctx.arc(e.x + e.radius/3, e.y + e.radius/4, e.radius/4, 0, Math.PI * 2);
                    ctx.fill();
                }
                else if (e.type === 'ufo') {
                    // 绘制UFO
                    ctx.fillStyle = '#aa44ff';
                    ctx.beginPath();
                    ctx.arc(e.x, e.y, e.radius, 0, Math.PI);
                    ctx.fill();

                    ctx.fillStyle = '#55eeff';
                    ctx.beginPath();
                    ctx.arc(e.x, e.y, e.radius/1.5, 0, Math.PI);
                    ctx.fill();

                    ctx.fillStyle = '#ff44aa';
                    ctx.beginPath();
                    ctx.arc(e.x - 8, e.y - 3, 3, 0, Math.PI * 2);
                    ctx.arc(e.x + 8, e.y - 3, 3, 0, Math.PI * 2);
                    ctx.fill();
                }
                else if (e.type === 'enemyShip') {
                    // 绘制敌舰
                    ctx.fillStyle = '#ff5555';
                    ctx.beginPath();
                    ctx.moveTo(e.x, e.y - 10);
                    ctx.lineTo(e.x - 15, e.y + 10);
                    ctx.lineTo(e.x + 15, e.y + 10);
                    ctx.closePath();
                    ctx.fill();

                    ctx.fillStyle = '#ff0000';
                    ctx.fillRect(e.x - 18, e.y, 5, 8);
                    ctx.fillRect(e.x + 13, e.y, 5, 8);
                }

                ctx.restore();
            }
        }

        // 绘制粒子
        function drawParticles() {
            for (let i = 0; i < particles.length; i++) {
                const p = particles[i];
                ctx.save();
                ctx.fillStyle = p.color;
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                ctx.fill();
                ctx.restore();
            }
        }

        // 绘制星星背景
        for (let i = 0; i < 100; i++) {
            bgStars.push({
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height,
                size: Math.random() * 2,
                brightness: Math.random() * 0.8 + 0.2
            });
        }

        // 绘制背景
        function drawBackground() {
            // 黑色背景
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制星星
            ctx.save();
            for (let i = 0; i < bgStars.length; i++) {
                const star = bgStars[i];
                ctx.fillStyle = `rgba(255, 255, 255, ${star.brightness})`;
                ctx.beginPath();
                ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
                ctx.fill();
            }
            ctx.restore();
        }

        // 玩家射击
        function shoot() {
            const now = Date.now();
            if (now - player.lastShot > player.fireRate) {
                bullets.push({
                    x: player.x,
                    y: player.y - 15,
                    width: 4,
                    height: 15,
                    speed: 12
                });
                player.lastShot = now;

                // 射击音效
                beep(200, 0.1);
            }
        }

        // 生成敌人
        function spawnEnemy() {
            const types = ['asteroid', 'ufo', 'enemyShip'];
            const type = types[Math.floor(Math.random() * types.length)];

            let enemy;
            const x = Math.random() * (canvas.width - 100) + 50;
            const y = -30;

            if (type === 'asteroid') {
                const size = Math.floor(Math.random() * 15) + 15;
                enemy = {
                    x: x,
                    y: y,
                    radius: size,
                    speed: Math.random() * 3 + 1,
                    type: 'asteroid',
                    health: Math.ceil(size / 10)
                };
            }
            else if (type === 'ufo') {
                enemy = {
                    x: x,
                    y: y,
                    radius: 15,
                    speed: Math.random() * 2 + 1,
                    type: 'ufo',
                    health: 2
                };
            }
            else {
                enemy = {
                    x: x,
                    y: y,
                    width: 30,
                    height: 20,
                    speed: Math.random() * 4 + 1,
                    type: 'enemyShip',
                    health: 3
                };
            }

            enemies.push(enemy);
        }

        // 生成爆炸粒子
        function createExplosion(x, y, color, count = 20) {
            for (let i = 0; i < count; i++) {
                particles.push({
                    x: x,
                    y: y,
                    size: Math.random() * 4 + 2,
                    speedX: (Math.random() - 0.5) * 5,
                    speedY: (Math.random() - 0.5) * 5,
                    color: color,
                    life: Math.random() * 30 + 20
                });
            }
        }

        // 简单音效
        function beep(frequency, duration) {
            try {
                const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioCtx.createOscillator();
                const gainNode = audioCtx.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(audioCtx.destination);

                oscillator.type = 'sine';
                oscillator.frequency.value = frequency;
                gainNode.gain.value = 0.1;

                oscillator.start();
                setTimeout(() => {
                    oscillator.stop();
                }, duration * 1000);
            } catch (e) {
                console.log('Audio not supported');
            }
        }

        // 碰撞检测
        function checkCollision(obj1, obj2) {
            // 圆形碰撞检测（用于陨石和UFO）
            if (obj1.radius && obj2.radius) {
                const dx = obj1.x - obj2.x;
                const dy = obj1.y - obj2.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                return distance < obj1.radius + obj2.radius;
            }

            // 矩形碰撞检测（用于玩家、敌舰和子弹）
            const rect1 = {
                x: obj1.x - (obj1.width || obj1.radius || 0),
                y: obj1.y - (obj1.height || obj1.radius || 0),
                width: (obj1.width || obj1.radius * 2 || 0),
                height: (obj1.height || obj1.radius * 2 || 0)
            };

            const rect2 = {
                x: obj2.x - (obj2.width || obj2.radius || 0),
                y: obj2.y - (obj2.height || obj2.radius || 0),
                width: (obj2.width || obj2.radius * 2 || 0),
                height: (obj2.height || obj2.radius * 2 || 0)
            };

            return rect1.x < rect2.x + rect2.width &&
                   rect1.x + rect1.width > rect2.x &&
                   rect1.y < rect2.y + rect2.height &&
                   rect1.y + rect1.height > rect2.y;
        }

        // 更新游戏状态
        function update() {
            // 移动玩家
            if (game.keys['ArrowLeft'] || game.keys['a']) {
                player.x = Math.max(player.x - player.speed, player.width / 2);
            }
            if (game.keys['ArrowRight'] || game.keys['d']) {
                player.x = Math.min(player.x + player.speed, canvas.width - player.width / 2);
            }

            // 玩家射击
            if (game.keys[' '] && game.running) {
                shoot();
            }

            // 移动子弹
            for (let i = bullets.length - 1; i >= 0; i--) {
                const b = bullets[i];
                b.y -= b.speed;

                // 移除超出屏幕的子弹
                if (b.y < 0) {
                    bullets.splice(i, 1);
                    continue;
                }

                // 检测子弹与敌机的碰撞
                for (let j = enemies.length - 1; j >= 0; j--) {
                    const e = enemies[j];
                    if (checkCollision(b, e)) {
                        // 击中敌人
                        e.health--;

                        // 创建击中粒子效果
                        createExplosion(b.x, b.y, '#ffff00', 5);

                        if (e.health <= 0) {
                            // 创建爆炸效果
                            createExplosion(e.x, e.y, '#ff5500');

                            // 增加分数
                            let points = 0;
                            if (e.type === 'asteroid') points = 10;
                            else if (e.type === 'ufo') points = 50;
                            else if (e.type === 'enemyShip') points = 100;

                            game.score += points;

                            // 每500分增加一条生命
                            if (Math.floor(game.score / 500) > Math.floor((game.score - points) / 500)) {
                                game.lives++;
                                livesDisplay.textContent = game.lives;
                                gameMessage.textContent = '额外生命!';
                                setTimeout(() => {
                                    if (game.running) gameMessage.textContent = '';
                                }, 2000);
                                beep(400, 0.2);
                                beep(600, 0.2);
                            }

                            // 移除敌机
                            enemies.splice(j, 1);

                            // 爆炸音效
                            beep(100, 0.1);
                            beep(80, 0.1);
                        }

                        // 移除子弹
                        bullets.splice(i, 1);
                        break;
                    }
                }
            }

            // 移动敌机
            for (let i = enemies.length - 1; i >= 0; i--) {
                const e = enemies[i];
                e.y += e.speed;

                // 检测敌机与玩家碰撞
                if (checkCollision(player, e)) {
                    // 创建爆炸效果
                    createExplosion(player.x, player.y, '#ff0000', 50);

                    // 减少生命
                    game.lives--;

                    // 碰撞音效
                    beep(150, 0.3);

                    // 移除敌机
                    enemies.splice(i, 1);

                    if (game.lives <= 0) {
                        gameOver();
                    }
                    continue;
                }

                // 移除超出屏幕的敌机
                if (e.y > canvas.height + 50) {
                    enemies.splice(i, 1);
                }
            }

            // 更新粒子
            for (let i = particles.length - 1; i >= 0; i--) {
                const p = particles[i];
                p.x += p.speedX;
                p.y += p.speedY;
                p.life--;

                if (p.life <= 0) {
                    particles.splice(i, 1);
                }
            }

            // 随机生成新敌机
            if (Math.random() < 0.03) {
                spawnEnemy();
            }

            // 更新分数显示
            scoreDisplay.textContent = game.score;
        }

        // 绘制游戏画面
        function draw() {
            drawBackground();
            drawPlayer();
            drawBullets();
            drawEnemies();
            drawParticles();
        }

        // 游戏循环
        function gameLoop() {
            if (game.running) {
                update();
                draw();
                requestAnimationFrame(gameLoop);
            }
        }

        // 开始游戏
        function startGame() {
            game.running = true;
            game.score = 0;
            game.lives = 3;
            game.level = 1;

            scoreDisplay.textContent = game.score;
            livesDisplay.textContent = game.lives;
            gameMessage.textContent = '消灭敌人！';

            bullets.length = 0;
            enemies.length = 0;
            particles.length = 0;

            startBtn.disabled = true;

            // 清除之前的游戏循环
            cancelAnimationFrame(gameLoop);

            // 开始新游戏循环
            gameLoop();

            setTimeout(() => {
                if (game.running) gameMessage.textContent = '';
            }, 2000);
        }

        // 重新开始游戏
        function restartGame() {
            game.running = false;
            startBtn.disabled = false;
            gameMessage.textContent = '按开始按钮开始游戏!';
        }

        // 游戏结束
        function gameOver() {
            game.running = false;
            gameMessage.textContent = `游戏结束! 最终得分: ${game.score}`;
            startBtn.disabled = false;
            beep(200, 0.5);
            setTimeout(() => beep(150, 0.5), 300);
            setTimeout(() => beep(100, 0.5), 600);
        }

        // 事件监听器
        startBtn.addEventListener('click', startGame);
        restartBtn.addEventListener('click', restartGame);

        document.addEventListener('keydown', function(e) {
            game.keys[e.key] = true;

            // 防止空格键滚动页面
            if (e.key === ' ') {
                e.preventDefault();
            }
        });

        document.addEventListener('keyup', function(e) {
            game.keys[e.key] = false;
        });

        // 初始绘制
        drawBackground();
        drawPlayer();

        // 绘制初始游戏标题
        ctx.save();
        ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
        ctx.font = '30px "Courier New", monospace';
        ctx.textAlign = 'center';
        ctx.fillText('太空激战', canvas.width / 2, canvas.height / 2.5);

        ctx.font = '18px "Courier New", monospace';
        ctx.fillText('使用 ← → 移动，空格键射击', canvas.width / 2, canvas.height / 2);

        ctx.font = '16px "Courier New", monospace';
        ctx.fillText('按开始按钮开始游戏', canvas.width / 2, canvas.height / 1.7);
        ctx.restore();
    </script>
</body>
</html>